package com.its.common.net.server.handler;

import cn.hutool.core.lang.Singleton;
import cn.hutool.extra.spring.SpringUtil;
import com.its.common.net.core.BaseNetHandlerExecutor;
import com.its.common.net.core.config.HandlerPoolAutoConfigure;
import com.its.common.net.core.config.NetHandlerThreadPoolConfig;
import com.its.common.net.core.dto.GenericNetDTO;
import com.its.common.net.core.handler.BaseGenericHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.DependsOn;

import javax.annotation.Resource;

/**
 * @Author xiaxp
 * @Date 9/2/22 17:23
 * @Description
 */
@Slf4j
@AutoConfigureAfter(HandlerPoolAutoConfigure.class)
@DependsOn("netHandlerThreadPoolConfig")
public class ServerHandlerExecutor extends BaseNetHandlerExecutor<Boolean> {

    private ServerHandlerExecutor() {
    }

    public static ServerHandlerExecutor getInstance() {
        return SpringUtil.getBean(ServerHandlerExecutor.class);
    }


    @Override
    protected Boolean doExec(Object... reqs) {
        try {
            BaseGenericHandler handler = (BaseGenericHandler)reqs[0];
            ChannelHandlerContext ctx = (ChannelHandlerContext)reqs[1];
            GenericNetDTO data = (GenericNetDTO)reqs[2];
            if (ReferenceCountUtil.refCnt(data.getData()) < 1) {
                ReferenceCountUtil.retain(data.getData());
            }
            handler.handleData(ctx, data);
        } catch (Exception e) {
            log.error(e.toString());
        }
        return Boolean.TRUE;
    }
}
